package com.briup.jz.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.briup.jz.bean.Product;
import com.briup.jz.bean.ProductExample;
import com.briup.jz.bean.extend.ProductExtend;
import com.briup.jz.dao.ProductMapper;
import com.briup.jz.dao.extend.ProductExtendMapper;
import com.briup.jz.service.IProductService;
import com.briup.jz.utils.CustomerException;

@Service
public class ProductServiceImpl implements IProductService {

	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private ProductExtendMapper productExtendMapper; 

	@Override
	public void saveOrUpdate(Product product) throws CustomerException {
		// TODO Auto-generated method stub
		if(product.getId()!=null) {
			productMapper.updateByPrimaryKey(product);
		} else {
			// 判断是否有同名的分类，如果有抛出异常
			ProductExample example = new ProductExample();
			example.createCriteria().andNameEqualTo(product.getName());
			List<Product> list = productMapper.selectByExample(example);
			if(list.size()>0) {
				throw new CustomerException("同名的产品已存在");
			}
			//插入到数据库
			productMapper.insert(product);
		}
	}

	@Override
	public List<Product> query(String name,String status,Long productCategoryId) {
		// 模板查询
		ProductExample example = new ProductExample();
		//条件
		ProductExample.Criteria criteria = example.createCriteria();
		if(name !=null){
			criteria.andNameLike("%"+name+"%");//模糊查询
		}
		if(status !=null) {
			criteria.andStatusEqualTo(status);
		}
		if(productCategoryId !=null) {
			criteria.andProductCategoryIdEqualTo(productCategoryId);
		}
		List<Product> list = productMapper.selectByExample(example);
		return list;
	}
  
	@Override
	public void deleteById(long id) throws CustomerException {
		// TODO Auto-generated method stub
		Product Product = productMapper.selectByPrimaryKey(id);
		if(Product == null) {
			throw new CustomerException("要删除的产品信息不存在");
		}
		productMapper.deleteByPrimaryKey(id);
	}

	//级联
	@Override
	public List<ProductExtend> queryCascade(String name, String status, Long produtCategoryId) {
		return productExtendMapper.select(name, status, produtCategoryId);
	}

	//分页
	@Override
	public List<ProductExtend> pageQuery(int page, int pageSize, String name, String status, Long produtCategoryId) {
		int pageIndex = (page-1)*pageSize;
		List<ProductExtend> productExtends = productExtendMapper.pageQuery(pageIndex,pageSize,name,status,produtCategoryId);
		return productExtends;
	}

	@Override
	public void online(Long id) {
		Product product = productMapper.selectByPrimaryKey(id);
		product.setStatus("正常");
		productMapper.updateByPrimaryKey(product);
	}

	@Override
	public void offline(Long id) {
		Product product = productMapper.selectByPrimaryKey(id);
		product.setStatus("下架");
		productMapper.updateByPrimaryKey(product);
	}
	
}
